# coding=utf8
from pywebio.input import *
from pywebio.output import *
import time, os
from pywebio.platform.flask import webio_view
from flask import Flask
from api import Operation
from card_bin import getBankNameType
from loguru import logger
import datetime


path = os.path.abspath("./log")
log_path = os.path.join(path, f"{datetime.date.today()}.txt")
logger.add(sink=log_path, rotation="00:00", encoding="utf-8")

user = Operation()
userUinList = []

@logger.catch
def kill_pid(port):  # 根据端口获取pid并关闭
    pid = os.popen(f'lsof -i :{port}')
    for item in pid.read().split(' '):
        if item.isdigit():
            os.popen(f'kill -9 {item}')

@logger.catch
def bmi():
    global userUinList
    data = input_group(
        "批量构造用户号",
        inputs=[
            input('用户组ID', name='input01', required=False),
            input('设置获取构造中账号数量', name='input01_1', value=10, type=NUMBER, required=True, help_text='默认获取10个'),
            actions(buttons=[
                {'label': '获取', 'value': '1'},
                {'label': '显示', 'value': '2'},
                {'label': '清空', 'value': '3'}
            ], name='action01'),

            checkbox(label='选择需进行操作的账号UIN(默认全选)', name='userUinList', options=[item['userUin'] for item in user.get_csv()],
                     value=userUinList if len(userUinList) else [item['userUin'] for item in user.get_csv()], inline=True),

            input('设置用户号年龄', name='input02', value=18, type=NUMBER, required=True, help_text= '年龄默认大于18岁'),
            actions(buttons=[
                {'label': '简化注册', 'value': '1'},
                {'label': '完整注册未实名', 'value': '2'},
                {'label': '纯外卡用户', 'value': '3'},
                {'label': '完整注册+身份证实名', 'value': '4'},
                {'label': '二类实名', 'value': '5'},
                {'label': '三类实名', 'value': '6'},
            ], name='action02', help_text=f'二类实名会绑定平安储蓄卡·招商信用卡 \n 三类实名会绑定平安储蓄卡·招商信用卡·浦发储蓄卡·中国信用卡'),

            input('设置零钱充值金额(元)', name='input03', value=99999, type=NUMBER, required=True, help_text='充值金额默认99999元'),
            actions(buttons=[
                {'label': '充值零钱', 'value': '1'},
            ], name='action03'),

            input('设置零钱通充值金额(元)', name='input04', value=3000, type=NUMBER, required=True, help_text='充值金额默认3000元'),
            actions(label='', buttons=[
                {'label': '开通零钱通1.5', 'value': '1'},
                {'label': '开通零钱通2.0', 'value': '2'},
                {'label': '充值零钱通', 'value': '3'},
            ], name='action04'),

            actions(label='', buttons=[
                {'label': '开通零钱提额', 'value': '1'},
                {'label': '影印件实名认证', 'value': '2'},
            ], name='action05'),

            actions(label='', buttons=[
                {'label': '开通分期', 'value': '1'},
            ], name='action051'),

            input('设置银行通充值金额(元)', name='input06', value=1000, type=NUMBER, required=True, help_text='充值金额默认1000元'),
            actions(label='', buttons=[
                {'label': '开通银行通', 'value': '1'},
                {'label': '充值银行通', 'value': '2'},
            ], name='action06', help_text='开通银行通会自动绑定一张平安银行储蓄卡'),

            actions(label='', buttons=[
                {'label': '开通分付', 'value': '1'},
                {'label': '添加分付白名单', 'value': '2'},
            ], name='action07'),

            actions(label='', buttons=[
                {'label': '解绑所有银行卡', 'value': '1'},
                {'label': '绑定一张外卡', 'value': '2'},
            ], name='action08'),

            # 亲属卡造号功能 暂不完善
            # actions(label='', buttons=[
            #     {'label': '赠送亲属卡', 'value': '1'},
            #     {'label': '显示亲属卡赠送数据', 'value': '2'},
            # ], name='action09'),

            actions(label='', buttons=[
                {'label': '晋中银行公告上线', 'value': '1'},
                {'label': '晋中银行公告下线', 'value': '2'},
            ], name='action10'),

            checkbox(label='批量绑定银行卡，勾选银行卡类型', name='action11', options=getBankNameType(), inline=True),
        ],
    )

    logger.debug(f"{data}")
    if data['action01']:
        if data['action01'] == '1':
            if data['input01']:
                user.clear_userdata()
                put_text(f'正在查询用户组: {data["input01"]}构造中账号')
                userDataList = user.get_userGroup(data["input01"], data["input01_1"])  # 获取所有’构造中‘的uin，保存到csv中
                put_text(f'已获取{len(userDataList)}个构造中用户号')
            else:
                put_text(f'未输入用户组ID')
        elif data['action01'] == '2':
            uindata = user.get_csv()  # 获取csv中所有的用户数据
            for item in range(len(uindata)):
                uindata[item]['Serial_No'] = item + 1
            put_table(
                [
                    [
                        put_text(item['Serial_No']),
                        put_text(item['userGroupId']),
                        put_text(item['userUin']),
                        put_text(item['userName']),
                        put_text(item['userAccId']),
                        put_link(name='账号链接',url=item['url'], new_window=True)
                    ] for item in uindata
                ],
                header=['序号', 'userGroupId', 'userUin', 'userName', 'accid', 'url']
            )
        elif data['action01'] == '3':
            user.clear_userdata()
            put_text('已清空数据')

    elif data['action10']:
        if data['action10'] == '1':
            put_text(f'晋中银行公告已下线')
        elif data['action10'] == '2':
            put_text(f'晋中银行公告已上线')

    else:
        put_processbar(name='put02')

        if len(data['userUinList']) == 0:   # 选中的账号yin
            put_text(f'无效输入，未选中任何账号UIN')
            return

        userUinDataList = []
        userUinList = data['userUinList']
        uindata = user.get_csv()  # 获取csv中所有的用户数据
        for item in uindata:
            if item['userUin'] in userUinList:
                userUinDataList.append(item)

        for item in range(len(userUinDataList)):
            userUinDataList[item]['Serial_No'] = item + 1

        for item in userUinDataList:
            serialno = item['Serial_No']
            userGroup = item['userGroupId']
            uin = item['userUin']
            wxid = item['userName']
            accid = item['userAccId']
            url = item['url']
            re = {'FToolName': '', 'FOpStatus': ''}

            if data['action02']:

                input02 = data["input02"]
                put_text(f'年龄为:{input02}岁') if item['Serial_No'] == 1 else 1

                if data['action02'] == '1':
                    put_text(f'简化注册') if item['Serial_No'] == 1 else 1
                    user.simplify(uin)  # "创建一个 "简化注册" 的账号

                elif data['action02'] == '2':
                    put_text(f'完整注册未实名') if item['Serial_No'] == 1 else 1
                    user.norealname(uin, age=input02)  # "创建一个 "完整注册未实名" 的账号

                elif data['action02'] == '3':
                    put_text(f'纯外卡用户') if item['Serial_No'] == 1 else 1
                    user.uservisa(uin)  # "创建一个 "纯外卡用户" 的账号

                elif data['action02'] == '4':
                    put_text(f'完整注册+身份证实名') if item['Serial_No'] == 1 else 1
                    user.applyment(uin, age=input02)  # "创建一个 "完整注册+身份证实名" 的账号, 指定年龄

                elif data['action02'] == '5':
                    put_text(f'二类实名+平安储蓄卡+招商信用卡') if item['Serial_No'] == 1 else 1
                    user.applyment_pro(uin, age=input02)  # "二类实名+平安储蓄卡+招商信用卡" 的账号

                elif data['action02'] == '6':
                    put_text(f'三类实名+平安储蓄卡+招商信用卡+浦发储蓄卡+中国信用卡') if item['Serial_No'] == 1 else 1
                    user.applyment_3(uin, age=input02)  # 创建一个 "三类实名+平安储蓄卡+招商信用卡+浦发储蓄卡+中国信用卡" 的账号

            elif data['action03']:  # 充值零钱
                if data['action03'] == '1' and data["input03"]:
                    put_text(f'零钱充值:{data["input03"]}元') if item['Serial_No'] == 1 else 1
                    re = user.account_recharge(uin, data["input03"])  # 账户充值零钱

            elif data['action04']:
                if data['action04'] == '1':
                    put_text(f'开通零钱通1.5') if item['Serial_No'] == 1 else 1
                    re = user.open_lqt_15(uin)    # "开通零钱通"
                elif data['action04'] == '2':
                    put_text(f'开通零钱通2.0') if item['Serial_No'] == 1 else 1
                    re = user.open_lqt_20(uin, accid)    # "开通零钱通"
                elif data['action04'] == '3' and data["input04"]:
                    put_text(f'充值零钱通:{data["input04"]}') if item['Serial_No'] == 1 else 1
                    re = user.lqt_buy(uin, fee_amount=data["input04"])    # "充值零钱通"

            elif data['action05']:
                if data['action05'] == '1':
                    put_text(f'开通零钱提额') if item['Serial_No'] == 1 else 1
                    re = user.yu_e_ti_e(uin,accid)    # "零钱提额"
                elif data['action05'] == '2':
                    put_text(f'影印件实名认证') if item['Serial_No'] == 1 else 1
                    re = user.orc_auth(uin)    # "影印件实名认证"

            elif data['action051']:
                if data['action051'] == '1':
                    put_text(f'开通分期') if item['Serial_No'] == 1 else 1
                    re = user.post_api_account_manage(uin, accid)    # "开通分期"


            elif data['action06']:
                if data['action06'] == '1':
                    put_text(f'开通银行通') if item['Serial_No'] == 1 else 1
                    re = user.open_yht(uin)    # 开通 银行通
                elif data['action06'] == '2':
                    put_text(f'充值银行通:{data["input06"]}元') if item['Serial_No'] == 1 else 1
                    user.post_api_yht_trade_in(accid, data["input06"])  # 充值 银行通
                    # put_text(f'暂不支持银行通充值') if item['Serial_No'] == 1 else 1


            elif data['action07']:
                if data['action07'] == '1':
                    put_text(f'开通分付') if item['Serial_No'] == 1 else 1
                    re = user.open_or_close_credict(uin)    # "开通分付"
                elif data['action07'] == '2':
                    put_text(f'添加分付白名单') if item['Serial_No'] == 1 else 1
                    re = user.set_creditinfo(uin)    # 添加 分付白名单

            elif data['action08']:
                if data['action08'] == '1':
                    put_text(f'解绑所有银行卡') if item['Serial_No'] == 1 else 1
                    re = user.unbind_bank_card(uin)    # "解绑所有银行卡"
                elif data['action08'] == '2':
                    put_text(f'绑定一张外卡') if item['Serial_No'] == 1 else 1
                    re = user.bind_waika(uin)    # "绑定一张外卡"

            # 亲属卡账号构造尚不完善
            # elif data['action09']:
            #     if data['action09'] == '1':
            #         if (item['Serial_No'] % 2) == 0:
            #             frienduin = uindata[item['Serial_No'] - 2]['userUin']
            #             friendwxid = uindata[item['Serial_No'] - 2]['userName']
            #             friendurl = uindata[item['Serial_No'] - 2]['url']
            #             item['frienduin'], item['friendwxid'], item['friendurl']  = frienduin, friendwxid, friendurl
            #             user.api_bind_honey_pay_card(uin, frienduin, wxid, friendwxid)
            #         else:
            #             continue
            #         put_text('赠送亲属卡') if item['Serial_No'] == 1 else 1
            #     elif data['action09'] == '2':
            #         put_text('显示亲属卡赠送数据') if item['Serial_No'] == 1 else 1
            #         if (item['Serial_No'] % 2) == 0:
            #             frienduin = uindata[item['Serial_No'] - 2]['userUin']
            #             friendwxid = uindata[item['Serial_No'] - 2]['userName']
            #             friendurl = uindata[item['Serial_No'] - 2]['url']
            #             item['frienduin'], item['friendwxid'], item['friendurl'] = frienduin, friendwxid, friendurl

            elif data['action11']:
                for bank_name_type in data['action11']:
                    bank_name = bank_name_type[:-3]
                    card_type = bank_name_type[-3:-1]
                    re = user.bind_card(uin, bank_name, card_type)
                    put_text(f'{uin}-{re["FToolName"]}-{re["FOpStatus"]}-{bank_name_type}')
                    re = {'FToolName': '', 'FOpStatus': ''}

            else:
                put_text(f'无效输入')
                break
            time.sleep(0.5)


            set_processbar(name='put02', value=serialno / len(userUinDataList), label='进度' + str(int(serialno / len(userUinDataList) * 100)) + '%')

            if len(item.values()) != 6:
                put_table([[
                    put_text(serialno),
                    put_text(userGroup),
                    put_text(uin),
                    put_text(wxid),
                    put_link(name='账号链接', url=url, new_window=True),
                    put_text(item['frienduin']),
                    put_link(name='赠卡方账号链接', url=item['friendurl'], new_window=True),
                ]]),
                continue
            else:
                put_table([[
                    put_text(serialno),
                    put_text(userGroup),
                    put_text(uin),
                    put_text(wxid),
                    put_text(f'{re["FToolName"]}-{re["FOpStatus"]}'),
                    put_link(name='账号链接', url=url, new_window=True)]]
                )



@logger.catch
def creat_start(port=5000):
    kill_pid(port)
    app = Flask(__name__)
    app.add_url_rule('/', 'webio_view', webio_view(bmi), methods=['GET', 'POST'])
    logger.debug(f"已启动：http://127.0.0.1:{port}")
    app.run(port=port)




if __name__ == '__main__':

    creat_start()
